<?php

class BookingController extends Controller {

    public function actionIndex() {
        try {
            date_default_timezone_set('UTC');
            /* lay thong tin khach san */
            $criteria = new EMongoCriteria;
            $criteria->name = $_GET['id'];
            $criteria->active = true;
            $getHotelInfo = Hotel::model()->find($criteria);
            if ($getHotelInfo) {
                $default_currency = strtoupper($getHotelInfo->default_currency);
                if (!Yii::app()->session['_default_currency']) {
                    Yii::app()->session['_default_currency'] = $default_currency;
                }
                Yii::app()->session['_hotel'] = $_GET['id'];
                $this->render('index', array('model' => $getHotelInfo));
            } else {
                echo "The hotel is not exists";
            }
        } catch (Exception $e) {
            echo $e;
            die;
        }
    }

    public function actionSearch() {
        try {
            date_default_timezone_set('UTC');
            $session = MyFunction::generateRandomString(28);
            Yii::app()->session['_owner'] = $session;
            $params['hotel'] = Yii::app()->session['_hotel'];
            $hotel_condition = new EMongoCriteria;
            $hotel_condition->name = $params['hotel'];
            if (isset($_GET['id'])) {
                $hotel_condition->name = $_GET['id'];
            }
            $hotel_info = Hotel::model()->find($hotel_condition);
            if (isset($_GET['fromDate'])) {
                $fromDate = $_GET['fromDate'];
                $params['mongoFromDate'] = MyFunction::getDate($fromDate);
            } else {
                $fromDate = date('d-m-Y', time());

                $params['mongoFromDate'] = MyFunction::getDate($fromDate);
            }
            if (isset($_GET['toDate'])) {
                $toDate = $_GET['toDate'];
                $params['mongoToDate'] = MyFunction::getDate($toDate);
            } else {
                $toDate = date('d-m-Y', time());
                $params['mongoToDate'] = MyFunction::getDate($toDate);
            }

            $night = self::mongoDateDiff($params['mongoFromDate'], $params['mongoToDate']);
            if (isset($_GET['adult'])) {
                $params['adult'] = $_GET['adult'];
                $adult = $params['adult'];
            } else if (isset($_POST['adult'])) {
                $params['adult'] = $_POST['adult'];
                $adult = $params['adult'];
            }
            if (isset($_GET['child'])) {
                $params['child'] = $_GET['child'];
                $child = $params['child'];
            } else if (isset($_POST['child'])) {
                $params['child'] = $_POST['child'];
                $adult = $params['child'];
            }
            if (isset($_GET['extrabed'])) {
                $extrabed = $_GET['extrabed'];
                $params['extrabed'] = $extrabed;
            } else {
                $extrabed = 0;
                $params['extrabed'] = $extrabed;
            }

            $url = Yii::app()->params['tanhailong'] . '/' . $params['hotel'] . '/select-a-room.html?fromDate=' . $fromDate . '&toDate=' . $toDate . '&adult=' . $params['adult'] . '&child=' . $params['child'] . '&extrabed=' . $params['extrabed'];
            $exchangeRates = MyFunction::convert_currency();
            if (isset($_GET['currency'])) {
                $change_currency = $_GET['currency'];
                Yii::app()->session['_change_currency'] = $change_currency;
                $this->redirect($url);
            } else {
                $change_currency = Yii::app()->session['_change_currency'] ? : 'VND';
                Yii::app()->session['_change_currency'] = $change_currency;
            }
            $change_currency_value = $exchangeRates['rates'][$change_currency]['sell'];
            /* convert USD (default currency) to VND */
            $currency_USD_rate = $exchangeRates['rates']['USD']['sell'];
            $default_currency_value = $exchangeRates['rates']['VND']['sell'];
            $params['exchangeRates'] = $currency_USD_rate * $default_currency_value / $change_currency_value;
            Yii::app()->session['_exchangeRate'] = $params['exchangeRates'];
            //$condition = new EMongoCriteria;
            //$condition->hotel = Yii::app()->session['_hotel'];
            //$getRoomTypeInfo = Roomtype::model()->findAll($condition);
            //$this->render('index', array('roomInfo', $getRoomTypeInfo));
            $room = self::getRoomRate($params);
            //echo "<pre>";print_r($room);die;
            if (isset($_POST['fromDate']) && isset($_POST['toDate']) && isset($_POST['roomtype']) && isset($_POST['promotion'])) {
                $checkIn = $_POST['fromDate'] ? : $fromDate;
                $checkOut = $_POST['toDate'] ? : $toDate;
                $roomtype = $_POST['roomtype'];
                $promotion = $_POST['promotion'];
                $extrabed = $_POST['extrabed'] ? : 0;
                $params['mongoFromDate'] = MyFunction::getDate($checkIn);
                $params['mongoToDate'] = MyFunction::getDate($checkOut);
                $room = self::getRoomRate($params);
                if ($checkIn !== '' && $checkOut !== '' && $roomtype !== '' && $promotion !== '') {
                    $booking = array();
                    $now = new MongoDate();
                    Yii::app()->session['_time'] = $now->sec;
                    $rate = 0;

                    foreach ($room[$roomtype]['promos'] as $key => $promo) {
                        if ($key == 'promos_' . $promotion) {
                            switch ($adult) {
                                case 1: $rate = $promo['singleNet'];
                                    break;
                                case 2: $rate = $promo['doubleNet'];
                                    break;
                                case 3: $rate = $promo['trippleNet'];
                                    break;
                                default: $rate = $promo['singleNet'];
                            }
                            $booking['exchangeRates'] = $room[$roomtype]['exchangeRates'];
                            $booking['promotionId'] = $promotion;
                            $booking['roomType'] = $room[$roomtype]['roomType'];
                            $booking['roomTypeName'] = $room[$roomtype]['roomName'];
                            $booking['rate'] = $rate;
                            $booking['bookedRooms'] = 1;
                            $booking['singleNet'] = $promo['singleNet'];
                            $booking['doubleNet'] = $promo['doubleNet'];
                            $booking['trippleNet'] = $promo['trippleNet'];
                            $booking['promotionName'] = $promo['promotion_name'];
                            $booking['promotionType'] = $promo['promotion_type'];
                            $booking['fromDate'] = $checkIn;
                            $booking['toDate'] = $checkOut;
                            $booking['mongoFromDate'] = $params['mongoFromDate']->sec;
                            $booking['mongoToDate'] = $params['mongoToDate']->sec;
                            $booking['hotel'] = Yii::app()->session['_hotel'];
                            $booking['amount_OR_percentage'] = $promo['amount_OR_percentage'];
                            $booking['benefits'] = $promo['benefits'];
                            $booking['adult'] = $adult;
                            $booking['children'] = $child;
                            $booking['extrabed'] = $extrabed;
                            $config_condition = new EMongoCriteria;
                            $config_condition->hotel = $booking['hotel'];
                            $config_condition->roomType = 'all';
                            $config = Config::model()->find($config_condition);
                            $booking['extraBed_price'] = $config['extraBed_adults'];
                            $booking['cancel1'] = $promo['cancel1'];
                            if (isset($promo['cancel2'])) {
                                $booking['cancel2'] = $promo['cancel2'];
                            }
                            if (isset($room['cancel3'])) {
                                $booking['cancel3'] = $promo['cancel3'];
                            }
                            //$booking['extrabedChild'] = $promo['extrabedChild'];
                            //$arrRoom['price'] = $value['price'];
                            $booking['currency'] = Yii::app()->session['_change_currency'];
                        }
                    }
                    Yii::app()->session['_bookedRoom'] = $booking;
                    $this->redirect(Yii::app()->params['tanhailong'] . '/' . Yii::app()->session['_hotel'] . '/payment.html');
                } else {
                    $this->redirect(Yii::app()->params['tanhailong']);
                }
            }

            krsort($room, -1);
            //echo "<pre>";print_r($room);die;
            $this->render('search', array(
                'params' => $room,
                'child' => $params['child'],
                'adult' => $params['adult'],
                'extrabed' => $params['extrabed'],
                'listCurrency' => $exchangeRates,
                'fromDate' => $fromDate,
                'toDate' => $toDate,
                'url' => $url,
                'hotel_info' => $hotel_info,
                'night' => $night
            ));
        } catch (Exception $e) {
            
        }
    }

    public function actionPayment() {
        date_default_timezone_set('UTC');
        $time = new MongoDate();
        $a = Booking::model()->find();
        $arr_booked = Yii::app()->session['_bookedRoom'];
        $checkout = MyFunction::getDate(date('d-m-Y', $arr_booked['mongoToDate']));
        if (isset($_GET['vehicle'])) {
            $booked_room = Yii::app()->session['_bookedRoom'];
            $total_date = $this->mongoDateDiff_3($booked_room['mongoFromDate'], $booked_room['mongoToDate']);
            $hotel = $_GET['id'] ? : Yii::app()->session['_hotel'];
            $hotel_condition = new EMongoCriteria;
            $hotel_condition->hotel = $hotel;
            $hotel_content = Content::model()->find($hotel_condition);
            /* config */
            $config = Config::model()->findByAttributes(array('hotel' => $hotel));

            $vehicle = $hotel_content['info']['airportTransferFee']['category'][$_GET['vehicle']]['value'] * Yii::app()->session['_exchangeRate'];
            if ($config && $config->offers_active && $total_date >= $config['pickup']) {
                echo CJSON::encode('0');
                return;
            } else {
                echo CJSON::encode(array(
                    'price' => $vehicle,
                    'vehicle' => number_format($vehicle, 2, '.', ','),
                    'currency' => Yii::app()->session['_change_currency']
                ));
                return;
            }
            //echo CJSON::encode(array('price' => $vehicle, 'vehicle' => number_format($vehicle, 2, '.', ','), 'currency' => Yii::app()->session['_change_currency']));
            //return;
        }
        if (isset($_GET['zip_code'])) {
            $zip_code = MyFunction::country_zip()[$_GET['zip_code']];
            echo CJSON::encode($zip_code);
            return;
        }
        if ($time->sec - Yii::app()->session['_time'] < 30000) {
            if (isset(Yii::app()->session['_bookedRoom'])) {
                $room = Yii::app()->session['_bookedRoom'];
                $flag = true;
                if (isset($_POST['continue_payment'])) {
                    /* kiem tra lai xem con phong khong */
                    $room_condition = new EMongoCriteria;
                    $room_condition->date = array(
                        '$gte' => $room['mongoFromDate'],
                        '$lt' => $room['mongoToDate']);

                    $room_condition->hotel = $room['hotel'];
                    $check_room = Room::model()->findAll($room_condition);
                    if (count($check_room) > 0) {
                        foreach ($check_room as $r) {
                            if (!$r->available || $r->available <= $r->usedTotalAllotment || $r->closeOutRegularAllot == true || ($r->noArrival == true && self::mongoDateDiff($r->date, $room['mongoFromDate']) == 0)) {
                                $flag = FALSE;
                                break;
                            }
                        }
                    }
                    $booking = new Booking;
                    $matchRoom = array();
                    $today = new MongoDate();
                    $flightInfo = array();
                    $guestdetails = array();
                    $contact = array();
                    $payment = array();
                    $airportInfo = array();
                    $airport_condition = new EMongoCriteria;
                    $airport_condition->hotel = $room['hotel'];
                    $airport_transfer = Content::model()->find($airport_condition);
                    /* select car */
                    if ($airport_transfer) {
                        $info = $airport_transfer->info;
                        if ($info['airportTransferAvailable']['status'] == 'on') {
                            $airportInfo['dropFee']['Cars0'] = '';
                            $airportInfo['dropFee']['Name0'] = '';
                            $airportInfo['dropFee']['Price0'] = '';
                            $airportInfo['dropFee']['Status0'] = '';
                            $airportInfo['dropFee']['Time0'] = '';
                            $airportInfo['tranferFee']['Cars0'] = $_POST['vehicle'];
                            $airportInfo['tranferFee']['Name0'] = 'Airport Pick Up Fee';

                            $total_date = $this->mongoDateDiff_3($room['mongoFromDate'], $room['mongoToDate']);

                            $config = Config::model()->findByAttributes(array('hotel' => $room['hotel']));
                            if ($config && $config->offers_active && $total_date >= $config['pickup']) {
                                $airportInfo['tranferFee']['Price0'] = 0;
                            } else {
                                $vehicle = $airport_transfer['info']['airportTransferFee']['category'][$_POST['vehicle']]['value'] * Yii::app()->session['_exchangeRate'];
                                $airportInfo['tranferFee']['Price0'] = $vehicle;
                            }
                            $airportInfo['tranferFee']['Time0'] = $_POST['arrival_time'];
                            if ($_POST['vehicle'] !== '') {
                                $airportInfo['tranferFee']['Status0'] = 1;
                            }
                        }
                    }

                    /* contact info */
                    $contact['gender'] = $_POST['gender'];
                    $contact['firstname'] = $_POST['name'];
                    $contact['lastname'] = '';
                    $contact['email'] = $_POST['email'];
                    $contact['phone'] = $_POST['zip_code'] . $_POST['phone'];
                    $contact['Country'] = $_POST['country_name'];
                    $contact['address'] = '';
                    /* payment method */
                    $payment['payment_detail'] = $_POST['card'];
                    $payment['card_number'] = $_POST['card_number'];
                    $payment['name_on_card'] = $_POST['card_holder'];
                    $expire = explode('-', $_POST['expire_date']);
                    $payment['cardmonth'] = $expire[1];
                    $payment['cardyear'] = $expire[2];
                    $payment['cvv'] = $_POST['cvv_number'];
                    $args2 = $room['mongoFromDate'] . $room['mongoToDate'];
                    $guestdetails[$args2][0]['firstname0'] = $_POST['name'];
                    $guestdetails[$args2][0]['lastname0'] = '';
                    /* Flight info */
                    $flightInfo['arrivalFilight0'] = $_POST['arrival_flight'];
                    $flightInfo['arrivalDate0'] = $_POST['arrival_date'];
                    $flightInfo['arrivalTime0'] = '';
                    $flightInfo['departureFilight0'] = '';
                    $flightInfo['departureTime0'] = '';
                    $flightInfo['departureDate0'] = '';
                    $flightInfo['status'] = '';
                    /* room info booking */
                    Yii::app()->session['_roomtype'] = $room['roomType'];
                    $matchRoom[$args2][0]['promotion_id'] = $room['promotionId'];
                    $matchRoom[$args2][0]['roomType'] = $room['roomType'];
                    $matchRoom[$args2][0]['roomTypeName'] = $room['roomTypeName'];
                    $matchRoom[$args2][0]['extrabed'] = $room['extrabed'];
                    $matchRoom[$args2][0]['bookNights'] = (strtotime($room['toDate']) - strtotime($room['fromDate'])) / 60 / 60 / 24;
                    $matchRoom[$args2][0]['promotion_name'] = $room['promotionName'];
                    $matchRoom[$args2][0]['promotion_type'] = $room['promotionType'];
                    if ($room['children'] > 0) {
                        
                    }
                    $matchRoom[$args2][0]['rate'] = $room['rate'] * $matchRoom[$args2][0]['bookNights'] + ($room['extrabed'] * $room['extraBed_price']);

                    $matchRoom[$args2][0]['price'] = $room['rate'] * $matchRoom[$args2][0]['bookNights'];
                    $matchRoom[$args2][0]['currency'] = $room['currency'];
                    $matchRoom[$args2][0]['amount_OR_percentage'] = $room['amount_OR_percentage'];
                    $matchRoom[$args2][0]['benefits'] = $room['benefits'];
                    $matchRoom[$args2][0]['adult'] = $room['adult'];
                    $matchRoom[$args2][0]['children'] = $room['children'];
                    /* cancel policy */
                    $matchRoom[$args2][0]['police']['cancel1'] = $room['cancel1'];

                    if (isset($room['cancel2'])) {
                        $matchRoom[$args2][0]['police']['cancel2'] = $room['cancel2'];
                    }
                    if (isset($room['cancel3'])) {
                        $matchRoom[$args2][0]['police']['cancel3'] = $room['cancel3'];
                    }
                    $booking->active = true;
                    $booking->requestDate = $today;
                    $booking->created = $today;
                    $booking->defaultCurrency = 'VND';
                    $booking->exchangeRates = $room['exchangeRates'];
                    $booking->hotel = $room['hotel'];
                    $booking->bookingStatus = "preBooking";
                    $booking->contact = $contact;
                    $booking->payment = $payment;
                    $booking->matchRoom = $matchRoom;
                    $booking->guestdetails = $guestdetails;
                    $booking->flightInfo = $flightInfo;
                    $booking->specialRequest = $_POST['request'];
                    $booking->airportInfo = $airportInfo;
                    $booking->checkout = $checkout;
                    $booking->owner_id = Yii::app()->session['_owner'];
                    $booking->currency = Yii::app()->session['_change_currency'];

                    $c = MyFunction::convert_currency();
                    $booking->changeCurrency = $c['rates'][Yii::app()->session['_change_currency']]['sell'];
                    /* delete all booking that same owner_id */
                    $delete_booking = Booking::model()->findAllByAttributes(array(
                        'hotel' => $room['hotel'],
                        'bookingStatus' => 'preBooking',
                        'owner_id' => Yii::app()->session['_owner']
                            ));
                    if ($delete_booking) {
                        foreach ($delete_booking as $dl) {
                            $dl->delete();
                        }
                    }
                    if ($booking->save()) {
                        //unset(Yii::app()->session['_bookedRoom']);
                        $this->redirect('confirm.html');
                    } else {
                        echo "Full";
                        $this->redirect(Yii::app()->params['tanhailong']);
                        //die;
                    }
                }
                $hotel_condition = new EMongoCriteria;
                $hotel_condition->hotel = $_GET['id'] ? : Yii::app()->session['_hotel'];
                $hotel_content = Content::model()->find($hotel_condition);
                $this->render('payment', array(
                    'room' => $room,
                    'flag' => $flag,
                    'hotel_content' => $hotel_content
                ));
            } else {
                $this->redirect(Yii::app()->params['tanhailong']);
            }
        } else {
            $this->redirect(Yii::app()->params['tanhailong']);
        }
    }

    public function actionConfirm() {
        if (Yii::app()->session['_owner']) {
            $booking = new EMongoCriteria;
            $booking->owner_id = Yii::app()->session['_owner'];
            $booked = Booking::model()->find($booking);
            if (isset($_POST['confirmation'])) {
                $booked->short_id = substr($booked->_id, 0, 8);
                $booked->bookingStatus = 'confirmBooking';
                $booked->version = 'mobile';
                $booked->new_notification = 1;
                $bookSave = $booked->save();
                if ($bookSave) {
                    $room = Yii::app()->session['_bookedRoom'];
                    $room_conditions = new EMongoCriteria;
                    $room_conditions->date = array(
                        '$gte' => MyFunction::getDate($room['fromDate']),
                        '$lt' => MyFunction::getDate($room['toDate'])
                    );
                    $room_conditions->roomType = $room['roomType'];
                    $room_conditions->hotel = $room['hotel'];
                    $rooms = Room::model()->findAll($room_conditions);
                    //echo "<pre>";print_r($rooms);die;
                    foreach ($rooms as $r) {
                        $r['usedTotalAllotment'] = $r['usedTotalAllotment'] + 1;
                        $r->save();
                    }
                }
                $hotel = $_GET['id'] ? : Yii::app()->session['_hotel'];
                $hotel_condition = new EMongoCriteria;
                $hotel_condition->name = $hotel;
                $hotel_info = Hotel::model()->find($hotel_condition);
                $hotel_content_condition = new EMongoCriteria;
                $hotel_content_condition->hotel = $hotel;
                $hotel_content = Content::model()->find($hotel_content_condition);
                $hotel_name = 'Silverland Central - Tan Hai Long Hotel & Spa';
                switch ($hotel) {
                    case 'silver-land-central-hotel-spa':
                        $cc = 'sales@tanhailonghotel.com.vn';
                        $hotel_name = 'Silverland Central - Tan Hai Long Hotel & Spa';
                        break;
                    case 'silverland-hotel-spa':
                        $cc = 'sales@silverlandhotel.com';
                        $hotel_name = 'Silverland Hotel & Spa';
                        break;
                    case 'silverland-boutique-hotel':
                        $cc = 'salesthl3@tanhailonghotel.com.vn';
                        $hotel_name = 'Silverland Boutique - Tan Hai Long 3 Hotel';
                        break;
                    case 'silverland-inn':
                        $cc = 'thl4@tanhailonghotel.com.vn';
                        $hotel_name = 'Silverland Inn - Tan Hai Long 4 Hotel';
                        break;
                    case 'grand-silverland-hotel-spa':
                        $cc = 'sales@grandsilverlandhotel.com';
                        $hotel_name = 'Grand Silverland Hotel & Spa';
                        break;
                    case 'la-jolie-hotel-spa':
                        $cc = 'sales@lajoliehotel.com';
                        $hotel_name = 'La Jolie Hotel & Spa';
                        break;
                    case 'silverland-sakyo-hotel-spa':
                        $cc = 'sales@sakyosilverlandhotel.com';
                        $hotel_name = 'Silverland Sakyo Hotel & Spa';
                        break;
                    default:
                        $cc = 'sales@tanhailonghotel.com.vn';
                        $hotel_name = 'Silverland Central - Tan Hai Long Hotel & Spa';
                }
                $message = new YiiMailMessage;
                $message->view = "email";
                $params = array(
                    'booked' => $booked,
                    'hotel_info' => $hotel_info,
                    'hotel_name' => $hotel_name,
                    'hotel_content' => $hotel_content);
                $message->subject = 'Confirmation for your booking';
                $message->setBody($params, 'text/html');
                $message->addBcc('dungtranhoang2004@hotmail.com');
                $message->addBCC('support@silverlandhotels.com');
                $message->addTo($booked['contact']['email']);
                $message->addReplyTo('no_reply@silverlandhotels.com', 'No Reply');
                $message->addFrom('no_reply@silverlandhotels.com', 'Thank you for your booking');
                //$cc = 'huytapptit@gmail.com';
                $message->cc = $cc;
                $result = Yii::app()->mail->send($message);
                if ($result) {
                    unset(Yii::app()->session['_roomtype']);
                    unset(Yii::app()->session['_bookedRoom']);
                    
                    $visitor_condition = new EMongoCriteria;
                    $visitor_condition->hotel = $hotel;
                    $visitor_condition->date = array(
                        '$gte' => MyFunctionCustom::getDate($date),
                        '$lt' => MyFunctionCustom::getDate(date('d-m-Y', strtotime("$date +1 day")))
                    );
                    $visitor_condition->ip = $_SERVER['REMOTE_ADDR'];
                    $visitor = Visitor::model()->find($visitor_condition);
                    $visitor->booked = $visitor->booked + 1;
                    $visitor->save();
                    
                    $this->redirect('thankyou.html?booking_id=' . Yii::app()->session['_owner']);
                }
            }
            $hotel_condition = new EMongoCriteria;
            $hotel_condition->name = Yii::app()->session['_hotel'];
            if (isset($_GET['id'])) {
                $hotel_condition->name = $_GET['id'];
            }
            $hotel_info = Hotel::model()->find($hotel_condition);
            if (Yii::app()->session['_bookedRoom']) {
                $room = Yii::app()->session['_bookedRoom'];
            }
            $this->render('confirm', array(
                'hotel_info' => $hotel_info,
                'booked' => $booked
            ));
        } else {
            $this->redirect(Yii::app()->params['tanhailong']);
        }
    }

    public function actionThankyou() {
        if (isset($_GET['booking_id'])) {
            $booking_condition = new EMongoCriteria;
            $booking_condition->owner_id = $_GET['booking_id'];
            $booking = Booking::model()->find($booking_condition);
            unset(Yii::app()->session['_owner']);
            unset(Yii::app()->session['_bookedRoom']);
            $hotel = $_GET['id'] ? : Yii::app()->session['_hotel'];
            $hotel_condition = new EMongoCriteria;
            $hotel_condition->name = $hotel;
            $hotel_info = Hotel::model()->find($hotel_condition);
            $this->render('thankyou', array(
                'hotel_info' => $hotel_info,
                'booking' => $booking
            ));
        } else {
            $this->redirect(Yii::app()->params['tanhailong']);
        }
    }

    public static function mongoDateDiff($date1, $date2) {
        $datetime1 = new DateTime(date(DEFAULT_DATE_FORMAT, $date1->sec));
        $datetime2 = new DateTime(date(DEFAULT_DATE_FORMAT, $date2->sec));
        $interval = $datetime1->diff($datetime2);
        return $interval->format('%a');
    }

    public static function mongoDateDiff_3($date1, $date2) {
        $datetime1 = new DateTime(date(DEFAULT_DATE_FORMAT, $date1));
        $datetime2 = new DateTime(date(DEFAULT_DATE_FORMAT, $date2));
        $interval = $datetime1->diff($datetime2);
        return $interval->format('%a');
    }

    public static function mongoDateDiff_2($date1, $date2) {
        $datetime1 = new DateTime(date(DEFAULT_DATE_FORMAT, $date1->sec));
        $datetime2 = new DateTime(date(DEFAULT_DATE_FORMAT, $date2->sec));
        $interval = $datetime1->diff($datetime2);
        return $interval;
    }

    public function getRoomRate(&$params) {
        $today = new MongoDate();
        $todayName = strtolower(date('D', $today->sec));
        $params['matchPromotions'] = array();
        $params['bookedNights'] = self::mongoDateDiff($params['mongoFromDate'], $params['mongoToDate']);
        $roomtype_conditions = new EMongoCriteria;
        $roomtype_conditions->hotel = $params['hotel'];
        $roomtype_conditions->status = '1';
        $roomtype_conditions->sort('order', EMongoCriteria::SORT_DESC);
        $getRoomTypes = Roomtype::model()->findAll($roomtype_conditions);

        foreach ($getRoomTypes as $roomType) {
            $params['order'][$roomType->roomType] = $roomType->order;
//            self::generateDateInterval($params, false);
//            RatesController::generateDateInterval($params, false);
        }
        //echo "<pre>";print_r($params['order']);die;
        $conditions = new EMongoCriteria;
        $conditions->hotel = $params['hotel'];
        $promotions = Promotion::model()->findAll($conditions);
        //echo "<pre>";print_r($promotions);die;
        foreach ($promotions as $promotion) {

            if (
                    (
                    (
                    $promotion->checkInFromDate <= $params['mongoFromDate'] &&
                    $params['mongoFromDate'] <= $promotion->checkInToDate
                    )
                    ||
                    (
                    $promotion->checkInFromDate < $params['mongoToDate'] &&
                    $params['mongoToDate'] < $promotion->checkInToDate
                    )
                    )
                    &&
                    (
                    (
                    $promotion->bookFromDate <= $today &&
                    $promotion->bookToDate > $today
                    )
                    ||
                    (
                    $promotion->bookFromDate <= $today &&
                    $promotion->bookToDate > $today
                    )
                    )
            ) {
                if ($promotion->promotion_type == 'early_bird') {
                    if (self::mongoDateDiff($params['mongoFromDate'], $today) >= $promotion->earlyDays)
                        $params['matchPromotions'][] = $promotion;
                } elseif
                ($promotion->promotion_type == 'last_minute') {
                    if (self::mongoDateDiff($params['mongoFromDate'], $today) <= $promotion->lastDays)
                        $params['matchPromotions'][] = $promotion;
                } else {
                    $params['matchPromotions'][] = $promotion;
                }
            }
        }
        $room_conditions = new EMongoCriteria;
        $room_conditions->date = array(
            '$gte' => $params['mongoFromDate'],
            '$lt' => $params['mongoToDate']);

        $room_conditions->hotel = $params['hotel'];
        $room_conditions->roomType = array('$ne' => 'all');
        $params['rooms'] = Room::model()->findAll($room_conditions);
        $types = array();
        if ($params['matchPromotions']) {
            foreach ($params['matchPromotions'] as $promo) {
                self::getAvailRoomType($types, $params, $promo);
            }
        } else {
            echo 'Het phong!';
            die;
            self::getAvailRoomType($types, $params);
        }
        return $types;
    }

    public function getAvailRoomType(&$types, $params, $promotion = NULL) {
        $hasPromotion = $promotion ? true : false;

        if ($hasPromotion) {
            $promotion_id = $promotion->_id->__toString();
        }
        $noAvailableRooms = array();
        $noPromo = array();
        $availableRooms = array();
        /* neu ngay den truoc ngay hien tai */
        $today = MyFunction::getDate(date('d-m-Y'));
        $compare = $this->mongoDateDiff_2($today, $params['mongoFromDate']);
        foreach ($params['rooms'] as $room) {
            $roomType = $room->roomType;
            $this->mongoDateDiff($room->date, $params['mongoFromDate']);
            if (!$room->available ||
                    ($room->available <= $room->usedTotalAllotment) ||
                    $room->closeOutRegularAllot ||
                    ($room->noArrival &&
                    self::mongoDateDiff($room->date, $params['mongoFromDate']) == 0) ||
                    $compare->invert == 1
            ) {
                $noAvailableRooms[$roomType] = $roomType;
            } elseif (!in_array($roomType, $noAvailableRooms) && !in_array($roomType, $availableRooms)) {
                $availableRooms[$roomType] = $roomType;
            }
            if (in_array($roomType, $noAvailableRooms)) {
                unset($availableRooms[$roomType]);
            }
        }
        /* check roomtype has exist in promotion? */
        if (isset($promotion['roomtype']) && $promotion['roomtype'] != '') {
            foreach ($promotion['roomtype'] as $promotion_roomtype => $p) {
                $promotion_roomtypes[$promotion_roomtype] = $promotion_roomtype;
            }
        }
        $language = Yii::app()->session['_lang'];
        /* Thong tin chung cua phong */
        $hotel = $params['hotel'];
        $RoomFacilities = array();
        /* lay thong tin cau hinh */
        $roomAvailable = array();
        foreach ($availableRooms as $key => $value) {
            $checkRoomtypes = Roomtype::model()->findByAttributes(array('status' => '1', 'roomType' => $key));
            if($checkRoomtypes){
            $occupancy_conditions = new EMongoCriteria;
            $occupancy_conditions->hotel = $params['hotel'];
            $Occupancies = Occupancy::model()->find($occupancy_conditions);
            //if ($Occupancies->$key->max >= $params['adult'] && $Occupancies->$key->children >= $params['child']) {
            if ($Occupancies['roomType'][$key]['max'] >= $params['adult'] &&
                    $Occupancies['roomType'][$key]['children'] >= $params['child']) {
                $roomAvailable[$key] = $value;
                /* lay thong tin phong */
                $roomType_conditions = new EMongoCriteria;
                $roomType_conditions->hotel = $hotel;
                $roomType_conditions->roomType = $value;
                $roomType_conditions->status = '1';
                $getRoomType = Roomtype::model()->find($roomType_conditions);
                /* Gia phong */
                $rate_conditions = new EMongoCriteria;
                $rate_conditions->date = array(
                    '$gte' => $params['mongoFromDate'],
                    '$lt' => $params['mongoToDate']);
                $rate_conditions->hotel = $hotel;
                $rate_conditions->roomType = $value;
                $rate = Rate::model()->findAll($rate_conditions);
                $rateCount = 1;
                $tempCount = 0;
                $singlePrice = $doublePrice = $tripplePrice = 0;
                foreach ($rate as $r => $v) {
                    $singlePrice += $rate[$r]['singleNet'];
                    $doublePrice += $rate[$r]['doubleNet'];
                    $tripplePrice += $rate[$r]['trippleNet'];
                    $tempCount = ($r + 1);
                }
                if ($tempCount !== 0)
                    $rateCount = $tempCount;
                /* tinh gia trung binh cong */
                $singleRates = $singlePrice / $rateCount;
                $doubleRates = $doublePrice / $rateCount;
                $trippleRates = $tripplePrice / $rateCount;
                /* ghi vao mang */
                $key = $params['order'][$key];
                $types[$key]['exchangeRates'] = $params['exchangeRates'];
                $types[$key]['roomType'] = $value;
                $types[$key]['roomName'] = $getRoomType['roomTypeName'];
                $types[$key]['singleNet'] = round($singleRates * $params['exchangeRates'], 2);
                $types[$key]['doubleNet'] = round($doubleRates * $params['exchangeRates'], 2);
                $types[$key]['trippleNet'] = round($trippleRates * $params['exchangeRates'], 2);
                $types[$key]['roomTypeId'] = $getRoomType->_id->{'$id'};
                $types[$key]['view'] = ucwords(Yii::t('lang', $getRoomType->view));
                $types[$key]['description'] = $getRoomType->roomDescription[$language];
                $types[$key]['maxPerRoom'] = $getRoomType->maxPerRoom;
                $types[$key]['cover_photo'] = $getRoomType['cover_photo'];
                foreach ($getRoomType->roomFacilities as $k => $rf) {
                    if ($rf !== '') {
                        $types[$key]['roomFacilities'][$k] = ucwords(Yii::t('lang', $k));
                    }
                }
                $types[$key]['roomSize'] = $getRoomType->roomSize;
                $types[$key]['roomSizeUnit'] = ucwords(Yii::t('lang', $getRoomType->roomSizeUnit));
                $item_condition = new EMongoCriteria;
                $item_condition->hotel = $hotel;
                $item_condition->type = $value;
                $item_condition->page = 'roomtype';
                $item_condition->published = true;
                $photos = Item::model()->findAll($item_condition);

                $i = 0;
                foreach ($photos as $pt => $pts) {
                    $types[$key]['photos'][$i]['photo_name'] = $pts->source;
                    $types[$key]['photos'][$i]['photo_title'] = $pts->title;
                    $i++;
                }
                if ($hasPromotion && !in_array($value, $noAvailableRooms) && in_array($value, $promotion_roomtypes)) {
                    /* cancel policy */
                    $types[$key]['promos']['promos_' . $promotion_id]['cancel1'] = Yii::t('lang', $promotion->cancelRules['cancel1']);
                    if ($promotion->cancelRules['cancel2'] !== 'nosecondrule') {
                        $types[$key]['promos']['promos_' . $promotion_id]['cancel2'] = Yii::t('lang', $promotion->cancelRules['cancel2']);
                    }
                    if ($promotion->cancelRules['cancel3'] !== 'nothirdrule') {
                        $types[$key]['promos']['promos_' . $promotion_id]['cancel3'] = Yii::t('lang', $promotion->cancelRules['cancel3']);
                    }
                    $types[$key]['promos']['promos_' . $promotion_id]['adult'] = $params['adult'];
                    $types[$key]['promos']['promos_' . $promotion_id]['child'] = $params['child'];
                    $types[$key]['promos']['promos_' . $promotion_id]['PromotionId'] = $promotion_id;
                    $types[$key]['promos']['promos_' . $promotion_id]['promotion_name'] = $promotion->promotion_name[$language];
                    $types[$key]['promos']['promos_' . $promotion_id]['promotion_type'] = $promotion->promotion_type;
                    $types[$key]['promos']['promos_' . $promotion_id]['roomTypeName'] = $getRoomType['roomTypeName'];
                    $types[$key]['promos']['promos_' . $promotion_id]['earlyDays'] = $promotion->earlyDays;
                    $types[$key]['promos']['promos_' . $promotion_id]['lastDays'] = $promotion->lastDays;
                    $types[$key]['promos']['promos_' . $promotion_id]['bookFromDate'] = $promotion->bookFromDate;
                    $types[$key]['promos']['promos_' . $promotion_id]['bookToDate'] = $promotion->bookToDate;
                    $types[$key]['promos']['promos_' . $promotion_id]['nightFrom'] = $promotion->nightFrom;
                    $types[$key]['promos']['promos_' . $promotion_id]['nightTo'] = $promotion->nightTo;
                    $types[$key]['promos']['promos_' . $promotion_id]['bookedRooms'] = $promotion->bookedRooms;
                    $types[$key]['promos']['promos_' . $promotion_id]['amount_OR_percentage'] = $promotion->amount_OR_percentage;
                    $types[$key]['promos']['promos_' . $promotion_id]['benefits'] = $promotion->benefits;
                    $types[$key]['promos']['promos_' . $promotion_id]['no1'] = $promotion->no1[$language];
                    $types[$key]['promos']['promos_' . $promotion_id]['no2'] = $promotion->no2[$language];

                    if ($room->promotionBlackout == true) {
                        $noPromo[$key] = $value;
                        if ($promotion->promotion_type == 'others' && $promotion->nightFrom == 1 && $promotion->amount_OR_percentage == 0) {
                            $types[$key]['promos']['promos_' . $promotion_id]['singleNet'] = round($types[$key]['singleNet'], 2);
                            $types[$key]['promos']['promos_' . $promotion_id]['doubleNet'] = round($types[$key]['doubleNet'], 2);
                            $types[$key]['promos']['promos_' . $promotion_id]['trippleNet'] = round($types[$key]['trippleNet'], 2);
                        }
                    } else if ($room->promotionBlackout == false && !in_array($value, $noPromo)) {
                        /* discount per night by percentage */
                        if ($promotion->benefits == 'percentage_discount_per_night') {
                            $discountSingleNet = $types[$key]['singleNet'] * (100 - $promotion->amount_OR_percentage) / 100;
                            $discountDoubleNet = $types[$key]['doubleNet'] * (100 - $promotion->amount_OR_percentage) / 100;
                            $discountTrippleNet = $types[$key]['trippleNet'] * (100 - $promotion->amount_OR_percentage) / 100;
                        }
                        /* discount per night by amount */ else if ($promotion->benefits == 'amount_discount_per_night') {
                            $discountSingleNet = $types[$key]['singleNet'] - $promotion->amount_OR_percentage;
                            $discountDoubleNet = $types[$key]['doubleNet'] - $promotion->amount_OR_percentage;
                            $discountTrippleNet = $types[$key]['trippleNet'] - $promotion->amount_OR_percentage;
                        }
                        /* discount per booking by amount */ else if ($promotion->benefits == 'amount_discount_per_booking') {
                            $discountSingleNet = $types[$key]['singleNet'];
                            $discountDoubleNet = $types[$key]['doubleNet'];
                            $discountTrippleNet = $types[$key]['trippleNet'];
                        }
                        /* free night */ else if ($promotion->benefits == 'free_nights') {
                            $discountSingleNet = $types[$key]['singleNet'];
                            $discountDoubleNet = $types[$key]['doubleNet'];
                            $discountTrippleNet = $types[$key]['trippleNet'];
                        } else {
                            $discountSingleNet = $types[$key]['singleNet'];
                            $discountDoubleNet = $types[$key]['doubleNet'];
                            $discountTrippleNet = $types[$key]['trippleNet'];
                        }
                        $types[$key]['promos']['promos_' . $promotion_id]['singleNet'] = round($discountSingleNet, 2);
                        $types[$key]['promos']['promos_' . $promotion_id]['doubleNet'] = round($discountDoubleNet, 2);
                        $types[$key]['promos']['promos_' . $promotion_id]['trippleNet'] = round($discountTrippleNet, 2);
                    }
                }
            }
        }
    }
    }

}

?>